import __config from '../config/env'
const request = (url, data) => {
  let showLoading = true;
  let _url = __config.basePath + url
  console.log('requestURL=========='+_url)
  console.log('requestData============='+JSON.stringify(data))
  return new Promise((resolve, reject) => {
    if (showLoading){
      wx.showLoading({
        title: '加载中',
        mask:true
      })
    }
    wx.request({
      url: _url,
      method: 'get',
      data: data,
      header: {
        //设置参数内容类型为x-www-form-urlencoded
        'content-type':'application/x-www-form-urlencoded',
        'Accept': 'application/json',
        'cookie':wx.getStorageSync("LtpaToken")||''
      },
      success(res) {
        if (res.statusCode == 200) {
          if (res.data.code != 200) {
            console.log(res.data)
            wx.showModal({
              title: '提示',
              content: res.data.info ? res.data.info : '没有数据' + '',
              showCancel:false,
              success() {
                
              },
              complete(){
                
              }
            })
            reject(res.data.msg)
          }
          resolve(res.data)
        } else if (res.statusCode == 404) {
          wx.showModal({
            title: '提示',
            content: '接口请求出错，请检查手机网络',
            showCancel:false,
            success(res) {
            }
          })
          reject()
        } else {
          console.log(res)
          wx.showModal({
            title: '提示',
            content: res.errMsg + ':' + res.data.message + ':' + res.data.msg,
            showCancel:false,
            success(res) {
              wx.reLaunch({
                url: '/pages/login/login',
              })
            }
          })
          reject()
        }
      },
      fail(error) {
        console.log(error)
        wx.showModal({
          title: '提示',
          content: '接口请求出错：' + error.errMsg,
          showCancel:false,
          success(res) {
            wx.reLaunch({
              url: '/pages/login/login',
            })
          }
        })
        reject(error)
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  })
}
const post = (url, data) => {
  let showLoading = true;
  let _url = __config.basePath + url
  console.log('requestURL=========='+_url)
  console.log('requestData============='+JSON.stringify(data))
  return new Promise((resolve, reject) => {
    if (showLoading){
      wx.showLoading({
        title: '加载中',
        mask:true
      })
    }
    wx.request({
      url: _url,
      method: 'POST',
      data: data,
      header: {
        //设置参数内容类型为x-www-form-urlencoded
        'content-type':'application/x-www-form-urlencoded',
        'Accept': 'application/json',
        'Cookie':wx.getStorageSync("LtpaToken")||''
      },
      success(res) {
        if (res.statusCode == 200) {
          if (res.data.code != 200) {
            console.log(res.data)
            wx.showModal({
              title: '提示',
              content: res.data.info ? res.data.info : '没有数据' + '',
              showCancel:false,
              success() {
                
              },
              complete(){
                
              }
            })
            reject(res.data.msg)
          }
          resolve(res.data)
        } else if (res.statusCode == 404) {
          wx.showModal({
            title: '提示',
            content: '接口请求出错，请检查手机网络',
            showCancel:false,
            success(res) {
            }
          })
          reject()
        } else {
          console.log(res)
          wx.showModal({
            title: '提示',
            content: res.errMsg + ':' + res.data.message + ':' + res.data.msg,
            showCancel:false,
            success(res) {
              wx.reLaunch({
                url: '/pages/login/login',
              })
            }
          })
          reject()
        }
      },
      fail(error) {
        console.log(error)
        wx.showModal({
          title: '提示',
          content: '接口请求出错：' + error.errMsg,
          showCancel:false,
          success(res) {
            wx.reLaunch({
              url: '/pages/login/login',
            })
          }
        })
        reject(error)
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  })
}
const upload = (url, data,filekey,filePath) => {
  let showLoading = true;
  let _url = __config.basePath + url
let params = Object.keys(data).map(function (key) {
        return encodeURIComponent(key) + "=" + encodeURIComponent(data[key]);
    }).join("&");
  console.log('requestURL=========='+_url)
  console.log('requestData============='+params)
  return new Promise((resolve, reject) => {
    if (showLoading){
      wx.showLoading({
        title: '加载中',
        mask:true
      })
    }
    wx.uploadFile({
      url: _url + '?' + params,
      filePath:filePath,
      name:filekey,
      formData: data,
      header: {
        'content-type':'multipart/form-data',
        'Accept': 'application/json',
        'cookie':wx.getStorageSync("LtpaToken")||''
      },
      success(res) {
        if (res.statusCode == 200) {
          if(res.data.code == undefined){
            res.data = JSON.parse(res.data);
          }
          if (res.data.code != 200) {
            wx.showModal({
              title: '提示',
              content: res.data.info ? res.data.info : '没有数据' + '',
              success() {
                
              },
              complete(){
                if(res.data.code == 401){
                  //session过期，则清除过期session，并重新加载当前页
                  // getApp().globalData.thirdSession = null
                  // wx.reLaunch({
                  //   url: getApp().getCurrentPageUrlWithArgs()
                  // })
                  wx.navigateTo({
                    url: '/pages/login/login',
                  })
                }
              }
            })
            reject(res.data.msg)
          }
          resolve(res.data)
        } else if (res.statusCode == 404) {
          wx.showModal({
            title: '提示',
            content: '接口请求出错，请检查手机网络',
            success(res) {

            }
          })
          reject()
        } else {
          console.log(res)
          wx.showModal({
            title: '提示',
            content: res.errMsg + ':' + res.data.message + ':' + res.data.msg,
            success(res) {
              wx.navigateTo({
                url: '/pages/login/login',
              })
            }
          })
          reject()
        }
      },
      fail(error) {
        console.log(error)
        wx.showModal({
          title: '提示',
          content: '接口请求出错：' + error.errMsg,
          success(res) {

          }
        })
        reject(error)
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  })
}

module.exports = {
  request,
  login: (data) => {//小程序登录接口
    return request('rpc/auth/login.json', data)
  },
  getMarkerOrg: (data) => {//获取营销组织
    return request('rpc/sale/list.json', {'act':'querytype',type:'MARKET_ORG'})
  },
  getStoreType: () => {//获取终端类型或者门店类型
    return request('rpc/sale/list.json', {'act':'querytype',type:'STORE_TYPE'})
  },
  getTerminalType: () => {//获取终端级别
    return request('rpc/sale/list.json', {'act':'querytype',type:'TERMINAL_LEVEL'})
  },
  getManageBrand: () => {//获取经营品牌
    return request('rpc/sale/list.json', {'act':'querytype',type:'MANAGE_BRAND'})
  },
  getManageType: () => {//获取经营品类
    return request('rpc/sale/list.json', {'act':'querytype',type:'MANAGE_TYPE'})
  },
  querystorebytype: (data) => {//获取门店列表
    return request('rpc/sale/list.json', {'act':'querystorebytype',type:data})
  },
  addstore: (data) => {//添加门店
    data.act = 'addstore'
    return request('rpc/sale/save.json', data)
  },
  getShopList: (data) => {//门店查询列表
    data.act = 'storevisitlist'
    return request('rpc/sale/list.json',data)
  },
  getShopDetail: (id) => {//门店详细信息
    return request('rpc/sale/list.json', {'act':'visitlist','storeid':id})
  },
  imgUpload : (filePath) =>{ //图片上传
    return upload('rpc/sale/saveimage.json',{},'image',filePath)
  },
  getMyOffLines: (data) => {//我的下线
    data.act = 'myoffline'
    return request('rpc/sale/list.json', data)
  },
  getMyPromlist: (storeid) => {//添加排班用户列表
    return request('rpc/sale/list.json', {'act':'promlist','storeid':storeid})
  },
  getSchedulelist: (data) => {//获取档期列表
    data.act = 'schedulelist'
    return request('rpc/sale/list.json', data)
  },
  addSchedule: (data) => {//保存排班计划
    data.act ='addSchedule'
    return request('rpc/sale/save.json', data)
  },
  saveSignin: (data) => {//签到
    data.act = 'signin'
    return request('rpc/sale/save.json', data)
  },
  savePaizhaoimage: (data) => {//保存店铺拍照
    data.act = 'paizhaoimage'
    return request('rpc/sale/save.json', data)
  },
  saveSignout: (data) => {//签退
    data.act = 'signout'
    return request('rpc/sale/save.json', data)
  },
  saveMyOffLine:(data) =>{ //业务对促销员进行审核、取消审核
    data.act = 'myoffline'
    return request('rpc/sale/save.json', data)
  },
  saveprom:(data) =>{ //促销员注册
    return request('rpc/sale/saveprom.json', data)
  },
  getStorepromvisitlist:(data) =>{ //获取排版列表
    data.act = 'storepromvisitlist'
    return request('rpc/sale/list.json', data)
  },
  getTempVisits:() =>{ //获取临时拜访记录
    let data = {}
    data.act = 'temvisit'
    return request('rpc/sale/list.json', data)
  },
  getTaskDetail:(gid) =>{ //获取任务明细列表
    let data = {}
    data.act = 'promvisitlist';
    data.gid = gid;
    return request('rpc/sale/list.json', data)
  },
  prompaizhaoimage:(data) =>{ //业务员的保存照片
    data.act = 'prompaizhaoimage'
    return request('rpc/sale/save.json', data)
  },
  getStoreList: (data) => {//获取门店列表
    data.act = 'storelist'
    return request('rpc/sale/list.json', data)
  },
  getUserid: () => {//获取用户账号
    return request('rpc/sale/getuserid.json')
  },
  savePromsignin: (data) => {//获取用户账号
    data.act = 'promsignin'
    return request('rpc/sale/save.json',data)
  },
  saveTemsignin: (data) => {//保存临时签到
    data.act = 'temsignin'
    return request('rpc/sale/save.json',data)
  },
  saveTemsignout: (data) => {//保存临时签退
    data.act = 'temsignout'
    return request('rpc/sale/save.json',data)
  },

  saveClocksignin: (data) => {//保存打卡签到
    data.act = 'clocksignin'
    return request('rpc/sale/save.json',data)
  },
  saveClocksignout: (data) => {//保存打卡签退
    data.act = 'clocksignout'
    return request('rpc/sale/save.json',data)
  },
  getRecordlist: (data) => {//获取记录
    data.act = 'recordlist'
    return request('rpc/sale/list.json',data)
  },
  updateUser: (data) => {//获取用户账号
    data.act = 'updateschedule'
    return request('rpc/sale/save.json',data)
  },
  getClocklist: (data) => {//打卡记录
    data.act = 'clocklist'
    return request('rpc/sale/list.json',data)
  },
  addJingpin: (data) => {//竞品收集
    return request('kuaixiao/goods/add1.json', data)
  },
  fetchGoods: (data) => {
    return request('kuaixiao/goods/fetch.json', data)
  },
  getUserInfo: (data) => {//获取用户信息
    data.act = 'userinformation'
    return request('rpc/sale/listinformation.json',data)
  },
  faceUpdate: (data) => {//更新人脸信息
    return post('kuaixiao/face/update.json',data)
  },
  faceSearch: (data) => {//人脸图片检查
    return post('kuaixiao/face/search/lincu.json',data)
  },
  bankcard: (data) => {//银行卡图片识别
    return post('kuaixiao/face/rec/bankcard.json',data)
  },
  idCard: (data) => {//身份证图片识别
    return post('kuaixiao/face/rec/idcard.json',data)
  },
  showIdcard: (data) => {//身份证图片识别
    return post('kuaixiao/face/rec/open.json',data)
  }
}